import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  message,Table,Dropdown,Menu,Button,Input ,Row,Col,Select,Popconfirm,Switch} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import moment from 'moment';
import {bind_change} from '../common/State';

import {BANNER_POSITION} from '../constants/index';


export default class Banner extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           loading:true,
        };
    }

    componentWillMount(){
        this.doFetch();
    }
    componentWillReceiveProps(nextProps){
        
    }
    async doFetch(page=1){
      let {search} = this.state;

      let result = await api('/operation/banner/list',{...search,page});

      if(result.cd!=0){
        message.error(result.msg);
        this.setState({loading:false})
        return;
      }
      this.setState({
          page,
          total:result.total,
          list:result.data,
          loading:false
      })
    }

    doSearch(){
      this.setState({
        loading:true
      })
      this.doFetch();
    }

    handleMenuClick(record,e){
      this.context.router.push(`/user/account/list?id=${record.id}&curType=${e.key}`)
    }

    //选择事件
    handleSelect(type,value){
        let {search} = this.state;
        search[type] = value;
        this.setState({search});
    }

    //删除事件
    async deleteById(record){
       let result =  await api('/operation/banner/delete',{id:record.id});
       if(result.cd !=0 ){
         message.error(result.msg);
         return;
       }
        message.success('删除成功',1,() => {
          let {page,list} = this.state;
          if(list.length==1&&page>1){page--}
          this.doFetch(page)
        })
    }
    

    //分页
    toPage({current:page,pageSize,total}){
      this.setState({loading:true})
      this.doFetch(page);
    }

    //状态操作
    async switchChange(record,status){
      this.setState({
        loading:true
      })
      let result = await api('/operation/banner/status',{id:record.id,status})
      if(result.cd!=0){
        message.error(result.msg);
        return
      }
      
      let {page} = this.state;
      this.doFetch(page)
    }

   
    render() {
        var {list, page,total,pageSize,loading,search}=this.state;
        return (
            <div >
                <NavBar navs={[{title:'Banner管理'}]} />
                <ContentBody className='container'>
                  <div className='search-panel'>
                      <Row gutter={16}>
                        <Col span={8}>
                          <label>banner名称:</label>
                          <Input 
                            {...this::bind_change('search.title')} 
                            placeholder="请输入banner名称" 
                          />
                        </Col>
                        <Col span={8}>
                          <label>banner位置:</label>
                          <Select 
                            value={search.type||""}
                            style={{ width: '100%' }} 
                            onChange={this.handleSelect.bind(this,'type')}
                          >
                            <Option value="">请选择</Option>
                            {
                              Object.keys(BANNER_POSITION).map((key,index) => {
                                return (
                                  <Option key={index} value={key}>{BANNER_POSITION[key]}</Option>
                                )
                              })
                            }
                          </Select>
                          
                        </Col>
                        <Col span={8}>
                          <label>启用状态:</label>
                          <Select 
                             value={search.status||""}
                            style={{ width: '100%' }} 
                            onChange={this.handleSelect.bind(this,'status')}
                          >
                            <Option value="">请选择</Option>
                            <Option  value={'1'}>启用</Option>
                            <Option  value={'2'}>关闭</Option>
                          </Select>
                        </Col>
                      </Row>
                      <div className='marginT20 text-center'>
                         <Button type="primary" onClick={this.doSearch.bind(this)} icon="search">查询</Button>
                         <Button 
                            type="primary" 
                            className='marginL20' 
                            onClick={()=>{
                              this.setState({
                                search:{}
                              })
                            }} 
                          >
                          重置
                          </Button>
                      </div>
                  </div>

                  <div className='marginB10'>
                      <Button 
                        type="primary" 
                        onClick={()=>{
                          this.context.router.push('/operation/banner/edit')
                        }}
                      >
                        创建新banner
                      </Button>
                  </div>  

                  <Table 
                    bordered
                    columns={this.getColumns()} 
                    simple 
                    dataSource={list}
                    pagination={{
                      current:page,
                      total,
                      pageSize,
                      showQuickJumper : true
                    }}
                    loading={loading}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={record => record.id}
                  />
                </ContentBody>
                  
            </div>
        );
    }

    getColumns(){

      let columns = [
            {
              title: 'banner名称',
              dataIndex: 'title',
              key: 'title',
            }, {
              title: '图片',
              dataIndex: 'save_url',
              key: 'save_url',
              width:80,
              render:(save_url) => {
                return <a href={save_url} target="_blank"><img width={80} height={80} src={save_url}/></a>
              }
            }, {
              title: '排序',
              dataIndex: 'position',
              key: 'position'
            },{
              title: 'banner位置',
              dataIndex: 'type',
              key: 'type',
              render:(type) => {
                return BANNER_POSITION[type]
              }
            }, {
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at'
            },{
              title: '启用状态',
              dataIndex: 'status',
              key: 'status',
              render:(status,record)=>{
                return (
                    <Switch 
                      checked={status==1?true:false} 
                      checkedChildren="开" 
                      unCheckedChildren="关" 
                      onChange={this.switchChange.bind(this,record)}
                    />
                  )
              }
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:100,
              render: (record) =>{
                  return (
                        <span>
                          <a 
                            href='javascript:void 0'
                            onClick={()=>{
                              this.context.router.push(`/operation/banner/edit?id=${record.id}`)
                            }}
                          >
                          编辑
                          </a>
                          <span className="ant-divider" />
                          <Popconfirm 
                            title="确定要删除?" 
                            onConfirm={this.deleteById.bind(this,record)} 
                            okText="确定" 
                            cancelText="取消"
                          >
                            <a href='javascript:void 0'>删除</a>
                          </Popconfirm>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}

Banner.contextTypes= { router: React.PropTypes.object.isRequired};

